package com.secneo.appshare.common;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import weibo4android.WeiboException;
import weibo4android.http.ImageItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.remind.RemindService;
import com.secneo.mp.http.HttpConnect;

public class ActivityUtil
{
	public static final String SERVER_SETTING = "server_setting";
	public static final String SERVER_URL = "url";
	public static final String SERVER_VERSION = "version";
	// 创建快捷方式
	private static final String ACTION_INSTALL_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT";
    //是否可以有多个快捷方式的副本
	static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
	public static boolean isEmpty(EditText... editTextes)
	{
		for (EditText et : editTextes)
		{
			if (et.getText() == null)
				return true;
			if (et.getText().toString().trim().equals(""))
				return true;
		}
		return false;
	}

	public static void alert(Context ctx, String msg)
	{
		try{
			new AlertDialog.Builder(ctx).setIcon(R.drawable.alert_dialog_icon).setTitle(R.string.alert_dialog_title).setMessage(msg).setPositiveButton(R.string.alert_dialog_button_ok, null).create()
						.show();			
		} catch (Exception ex){
			ex.printStackTrace() ;
		}
	}
	
/*	private static String getRandomB(Context ctx)
	{
		Random ran=new Random();
		int i=ran.nextInt(8);
		return ctx.getString(R.string.random_1+i);
	}*/

	public static void shareToWeibo(Context ctx, int actionType, String appName, String comment, 
			byte[] imageBytes, String atWho, String appIconUrl, String appDes, String pkgName)
	{
		Log.d("MyTag", "Begin shareToWeibo, type = " + actionType);

		boolean available = LocalStore.getLocaleStoreInstance().thereIsSnsAccountLogin();
		if(!available){
			return;
		}
		
		try
		{
			String txt = null;
			String str = null;
			String renrenStr = null;
			
			String downloadLink = null ;
			String finishingWord = null;
			if(pkgName != null)
			{
				downloadLink = ctx.getString(R.string.download_link , pkgName) ;
			}
			else
			{
				downloadLink = ctx.getString(R.string.download_link_no_pkgname) ;
			}

			finishingWord = ctx.getString(R.string.finishing_word) ;
			
			if (actionType == Constants.UPLOAD_ACTION_SHARE_WEIBO)
			{
				if (atWho == null)
				{
					str = ctx.getString(R.string.action_share_weibo, appName);
				}
				else
				{
					//str = ctx.getString(R.string.action_share_weibo_at, msg, atWho);
					str = ctx.getString(R.string.action_share_weibo_at, appName);
				}

				renrenStr = str + "  " + appDes + finishingWord;
				str = str + "(" + downloadLink + " )" + "  " + appDes + finishingWord;
			} 
			else if (actionType == Constants.UPLOAD_ACTION_DOWN)
			{
				str = ctx.getString(R.string.action_down, appName);
				renrenStr = str + "  " + appDes + finishingWord;
				str = str + "(" + downloadLink + " )" + " " + appDes + finishingWord;
			}
			else if (actionType == Constants.UPLOAD_ACTION_LOGIN)
			{
				str = ctx.getString(R.string.suggest_app);
				renrenStr = str;
			}
			else if (actionType == Constants.UPLOAD_ACTION_LIKE)
			{
				str = ctx.getString(R.string.action_like, appName);
				renrenStr = str + "  " + appDes + finishingWord;
				str = str + "(" + downloadLink + " )" + " " + appDes + finishingWord;
			}
			else if (actionType == Constants.UPLOAD_ACTION_TALK)
			{
				str = ctx.getString(R.string.action_talk, appName+":"+comment);
				renrenStr = str + "  " + finishingWord;
				str = str + "  (" + downloadLink + " )" + " " + finishingWord;
			}
			

			txt = URLEncoder.encode(str, "UTF-8");	
			Log.d("MyTag", "weibo str = " + txt);
			
			ImageItem pic=null;
			if(null!=imageBytes){
				pic = new ImageItem("pic", imageBytes);
			}
			
			if(imageBytes == null)
			{
				LocalStore.getLocaleStoreInstance().uploadAccountStatus(renrenStr, txt, false, pic, 
						appIconUrl, appName, actionType, downloadLink);
			}
			else
			{
				LocalStore.getLocaleStoreInstance().uploadAccountStatus(renrenStr, txt, true, pic, 
						appIconUrl, appName, actionType, downloadLink);
			}

		} catch (WeiboException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	
	
	public static void userShare(final Context ctx,String appName,int type)
	{
		
		String appNames=ctx.getResources().getString(R.string.share_contents, 
				appName== null||"".equals(appName) ?"" : appName);
        Intent it = new Intent(Intent.ACTION_SEND);
		it.putExtra(Intent.EXTRA_EMAIL, "");
		if(1==type)
		{
			it.putExtra(Intent.EXTRA_TEXT,appNames);
		}else
		{
			it.putExtra(Intent.EXTRA_TEXT,appName);
		}
		it.setType("text/plain");
		ctx.startActivity(Intent.createChooser(it, "Choose Email Client"));
	}
	
	
	
	
	
	
	
	
	//在所有需要连接网络的操作（例如梆梆推荐、升级、更多）前，首先检测是否存在可用网络
	public static boolean networkAvailable(final Context context)
	{
		if(getNetworkState(context) == 0)
		{
			final AlertDialog dialog = new AlertDialog.Builder(context).create();
			LayoutInflater inflater = LayoutInflater.from(context);
			View backupExpandHeader = inflater.inflate(R.layout.sec_opt_scan_stop_dialog, null);
			TextView popTitle = (TextView) backupExpandHeader.findViewById(R.id.popDialogTitle);
			popTitle.setText(context.getResources().getString(R.string.network_error));
			TextView popInfo = (TextView) backupExpandHeader.findViewById(R.id.popDialogInfo);
			popInfo.setText(context.getResources().getString(R.string.network_error_alert));
			dialog.show();
			dialog.setContentView(backupExpandHeader);

			Button okButton = (Button) backupExpandHeader.findViewById(R.id.ButtonOK);
			okButton.setText(context.getResources().getString(R.string.network_setting));
			okButton.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					Intent it = new Intent(Settings.ACTION_WIRELESS_SETTINGS);				
					context.startActivity(it);
					dialog.dismiss();
				}
			});

			Button cancelButton = (Button) backupExpandHeader.findViewById(R.id.ButtonCancel);
			cancelButton.setText(context.getResources().getString(R.string.network_return));
			cancelButton.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					dialog.dismiss();
				}
			});
			return false;
		}
		else
			return true;
	}

	
//检测网络状态 返回 0：无网络连接 1：WIFI 2:GPRG 3:3G或其它网络
	public static int getNetworkState(Context context) 
	{
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) 
            return 0;
        else 
        {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if(info == null || !info.isAvailable())
                return 0;
            else if(info.getTypeName().toUpperCase().equals("WIFI"))
                return 1;
            else if(info.getTypeName().toUpperCase().equals("GPRS"))
                return 2;
            else
                return 3;
        }
    }
	
	
	 // Get new policy for url
    public static void getPolicyUrl(final Context context)
    {
       SharedPreferences saving = context.getSharedPreferences(SERVER_SETTING, 0);
       String currentUrl = saving.getString(SERVER_URL, "");
       if(currentUrl.equals(""))
       {
           saving.edit().putString(SERVER_URL, Constants.ORIGINAL_URL).commit();
           currentUrl = Constants.ORIGINAL_URL;
       }
       String currentVersion = saving.getString(SERVER_VERSION, "");
       if(currentVersion.equals(""))
       {
           saving.edit().putString(SERVER_VERSION, Constants.ORIGINAL_VERSION).commit();
           currentVersion = Constants.ORIGINAL_VERSION;
       }
       String server_url = "http://" + currentUrl + Constants.POLICYSERVER_FOLLOW + currentVersion;
       try 
       {
           HttpConnect http = new HttpConnect();
           String result = http.connectByGetString(server_url, null);
           Log.d("MyTag", "Get policy = "+result);
           if (result == null || result.equals("") || result.equals("2001")) 
           {
              Log.d("MyTag", "no new policy found");
           }
           else
           {
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              DocumentBuilder dbuilder = dbf.newDocumentBuilder();
              InputSource is = new InputSource(new StringReader(result));
              is.setEncoding("UTF-8");
              Document dom = dbuilder.parse(is);
              String newUrl = dom.getElementsByTagName("ip").item(0).getAttributes().getNamedItem("data").getNodeValue();
              String version = dom.getElementsByTagName("version").item(0).getAttributes().getNamedItem("data").getNodeValue();
			Constants.DEFAULT_URL_TEMP = newUrl;
              saving.edit().putString(SERVER_URL, newUrl).commit();
              saving.edit().putString(SERVER_VERSION, version).commit();
              Log.d("MyTag", "newUrl ="+newUrl+" version ="+version);
           }
       }
       catch (MalformedURLException e1) {

       } catch (ParserConfigurationException e) {

       } catch (IOException e) {

       } catch (SAXException e) {

       }
    }
	/* 时间转换 */
	public static String transferTimeFormat(final Context ctx, String oldTime) throws ParseException
	{
		String newTime = "";
		if(oldTime == null || oldTime.length()==0)
			return newTime;
		SimpleDateFormat aa =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar time = Calendar.getInstance();
		time.setTime(aa.parse(oldTime));
		
		Calendar curr = Calendar.getInstance();
		long timeGapInMin = (curr.getTimeInMillis() - time.getTimeInMillis())/60000;
		
		if(timeGapInMin <= 0)
		{
			newTime = ctx.getString(R.string.time_now);
		}
		else if(timeGapInMin>0 && timeGapInMin<60)
		{
			int min = (int) (timeGapInMin/1);
			newTime = Integer.toString(min) + ctx.getString(R.string.time_min);
		}
		else if(timeGapInMin>=60 && timeGapInMin<=1440)
		{
			int hour = (int) (timeGapInMin/60);
			newTime = Integer.toString(hour) + ctx.getString(R.string.time_hour);
		}
		else
		{
			int day = (int) (timeGapInMin/(60*24));
			newTime = Integer.toString(day) + ctx.getString(R.string.time_day);
		}
		return newTime;
	}
	
	
	
	public static void showToast(Activity activity, String toastTitle,
			String toastContent) {
		LayoutInflater inflater = activity.getLayoutInflater();
		View layout = inflater.inflate(R.layout.custom_toast, null);

		TextView title = (TextView) layout.findViewById(R.id.ToastTileTextView);
		TextView content = (TextView) layout
				.findViewById(R.id.ToastContentTextView);
		title.setText(toastTitle);
		content.setText(toastContent);
		Toast toast = new Toast(activity.getApplicationContext());
		toast.setGravity(Gravity.RIGHT | Gravity.TOP, 12, 180);
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(layout);
		toast.show();
	}

	/*
	 * 创建快捷方式
	 */
	public static void creatShortcut(Context context,String appName,Drawable shortcutIcon,String packageName,String startActivityName) 
	{
		String str1 = "android.intent.extra.shortcut.ICON";
		Bitmap shortcutBmp = ActivityUtil.drawableToBitmap(shortcutIcon);
		Intent shortcutIntent = new Intent(ACTION_INSTALL_SHORTCUT);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);
		shortcutIntent.putExtra(EXTRA_SHORTCUT_DUPLICATE, false);
		Intent intent2 = new Intent(Intent.ACTION_MAIN);
		intent2.setComponent(new ComponentName(packageName, startActivityName));
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
		if("com.secneo.appshare.activities.SplashActivity".equals(startActivityName))
		{
			shortcutIntent.putExtra(str1,shortcutBmp);
		}else
		{
			Bitmap b=zoomBitmap(shortcutBmp,48,48);
			shortcutIntent.putExtra(str1, b);
		}
		context.sendBroadcast(shortcutIntent);
	}
	
	
	
	/** 
	 * 删除程序的快捷方式 
	 */  
	public static void delShortcut(Context context,String appName){  
	    Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");  
	          
	    //快捷方式的名称  
	    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,appName);  
	          
	    //指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer  
	    //注意: ComponentName的第二个参数必须是完整的类名（包名+类名），否则无法删除快捷方式  
	    String appClass = "com.secneo.appshare.activities.UserAppActivity";  
	    ComponentName comp = new ComponentName(Constants.PACKAGENAME, appClass);  
	    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));  
	    context.sendBroadcast(shortcut);  
	}  


	  // 放大缩小图片
    public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) 
    {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth =   ((float) w) / width;   
        float scaleHeight = ((float) h) / height;
        //matrix.setScale(scaleWidth,scaleHeight);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        return newBmp;
    }


	// drawable转换Bitmap
	public static Bitmap drawableToBitmap(Drawable drawable) {

		Bitmap bitmap = Bitmap
				.createBitmap(
						drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight(),
						drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
								: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		// canvas.setBitmap(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
				.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}
	
	// Bitmap → byte[]
    public static byte[] Bitmap2Bytes(Bitmap bm){  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();    
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);    
        return baos.toByteArray();  
    }  
	
    
   /**  
    *   
    * @param src 原图片  
    * @param watermark  要打的水印图片  
    * @return Bitmap 打好水印的图片  
    */  
   public static Bitmap createBitmap(Bitmap src,Bitmap watermark){   
    if(src == null){   
        return null;   
      }   
      int srcWidth = src.getWidth();   
      int srcHeight = src.getHeight();   
         
      int waterWidth = watermark.getWidth();   
      int waterHeight = watermark.getHeight();   
      //create the new blank bitmap   
      Bitmap newb = Bitmap.createBitmap(srcWidth,srcHeight,Config.ARGB_8888);//创建一个新的和src长度宽度一样的位图   
      Canvas cv = new Canvas(newb);   
      cv.drawBitmap(src, 0, 0,null);//在0,0坐标开始画入src   
      /*Paint paint = new Paint();  
      paint.setColor(Color.RED);*/  
      if(watermark != null){   
          cv.drawBitmap(watermark, srcWidth-waterWidth,srcHeight-waterHeight, null);//在src的右下解画入水印图片   
          //cv.drawText("HELLO",srcWidth-waterWidth,srcHeight-waterHeight, paint);//这是画入水印文字，在画文字时，需要指定paint   
      }   
      cv.save(Canvas.ALL_SAVE_FLAG);//保存   
      cv.restore();//存储   
      return newb;   
  }  

	/**
	 *  卸载一个程序
	 *  @param activity
	 *  @param packageName
	 */
	public static void uninstallApp(Activity activity,String packageName)
	{
		 try { 
			 Intent it = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + packageName));//packageName为程序包名
			 activity.startActivity(it);
			// activity.finish();
		  } catch (Exception e) {
		  // TODO Auto-generated catch block
			  e.printStackTrace();
			  Log.d("TAG...NameNotFoundException","name is not fond");
		  }
		
	}
	
	

	/*
	 * 验证邮箱
	 */
	public static boolean isEmail(String strEmail) {
		String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";

		Pattern p = Pattern.compile(strPattern);
		Matcher m = p.matcher(strEmail);
		return m.matches();
	}
	/*
	 * 菜单退出
	 */
	
	public static void closeSelfApp(final Context context)
	{
		          Log.d("MyTag", "closeSelfApp=closeSelfApp");
				com.secneo.mp.api.database.DatabaseHelper dh=new com.secneo.mp.api.database.DatabaseHelper(context);
				dh.insertUserAppPopularityByClose(context,101);
		        dh.close();
		        
		        Intent intent = new Intent(context, RemindService.class) ;
		        context.stopService(intent) ;
		        AppShareApplication.getInstance().exit();	

	}
	public static boolean isNumeric(String str)
    {
          Pattern pattern = Pattern.compile("[0-9]*");
          Matcher isNum = pattern.matcher(str);
          if( !isNum.matches() )
          {
                return false;
          }
          return true;
    }

	/**
      * 获取字符串的长度，如果有中文，则每个中文字符计为2位
	       *
	       * @param value
	     *            指定的字符串
	       * @return 字符串的长度
	       */
	      public static int chineseLength(String value) {
	          int valueLength = 0;
	         String chinese = "[\u0391-\uFFE5]";
	         /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
	        for (int i = 0; i < value.length(); i++) {
	             /* 获取一个字符 */
	            String temp = value.substring(i, i + 1);
	             /* 判断是否为中文字符 */
	             if (temp.matches(chinese)) {
	                 /* 中文字符长度为2 */
	                 valueLength += 2;
	             } else {
	                 /* 其他字符长度为1 */
	                valueLength += 1;
	             }
	         }
	         return valueLength;
	     }
}
